//
//  HealthDetailsViewController.m
//  safeLady
//
//  Created by Justsoso on 2017/7/14.
//  Copyright © 2017年 xmy. All rights reserved.
//

#import "HealthDetailsViewController.h"
#import "HealthDetailsViewModel.h"
#import "LoveTimesCollectionViewCell.h"

@interface HealthDetailsViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>

@property (nonatomic, strong) UIView *backgroundView;

@property (nonatomic, strong) UIView *topView;
@property (nonatomic, strong) UIImageView *topImageView;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UILabel *contentLabel;
@property (nonatomic, strong) CAShapeLayer *archLine;

@property (nonatomic, strong) UILabel *pregnancyDataLabel;
@property (nonatomic, strong) UILabel *dysmenorrheaDataLabel;
@property (nonatomic, strong) UILabel *statusDataLabel;
@property (nonatomic, strong) UILabel *phDataLabel;
@property (nonatomic, strong) UILabel *privateTightDataLabel;
@property (nonatomic, strong) UILabel *temperatureDataLabel;

@property (nonatomic, strong) UICollectionView *loveTimesCollectionView;

@property (nonatomic, strong) NSArray *loveTimes;
@property (nonatomic, strong) NSDictionary *healthDic;

@property (nonatomic, strong) HealthDetailsViewModel *viewModel;


@end

@implementation HealthDetailsViewController
@synthesize viewModel = _viewModel;

- (NSArray *)loveTimes {
    if (!_loveTimes) {
        _loveTimes = [NSArray array];
    }
    return _loveTimes;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"我的生理";
    
    self.view.backgroundColor = [UIColor colorWithHex:0xF7F7F7];
    [[[self.navigationController.navigationBar subviews] objectAtIndex:0] setAlpha:0];
    
    self.backgroundView = [[UIView alloc] initWithFrame:CGRectMake(10, 74, self.view.width-20, self.view.height-94)];
    self.backgroundView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.backgroundView];
    
    
    self.backgroundView.cornerRadius = 20;
    self.backgroundView.shadowColor = [UIColor lightGrayColor];
    self.backgroundView.shadowOffset = CGSizeMake(0, 2);
    self.backgroundView.shadowRadius = 4;
    self.backgroundView.shadowOpacity = 0.9;
    
    [self addTopView];
    
    [self addLoveTimesView];
    
    [self addHealthData];
    
}


- (void)addTopView {
    
    self.topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.backgroundView.width, self.backgroundView.height / 3 + H(50))];
    self.topView.backgroundColor = [UIColor clearColor];
    
    [self.backgroundView addSubview:self.topView];
    
    self.topImageView = [[UIImageView alloc] init];
    self.topImageView.backgroundColor = [UIColor colorWithHex:0xB0B2C9];
    self.topImageView.cornerRadius = H(20);
    [self.topView addSubview:self.topImageView];
    [self.topImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.topView.mas_centerX);
        make.bottom.equalTo(self.topView.mas_centerY).offset(-10);
        make.width.height.equalTo(@(H(40)));
    }];
    
    self.titleLabel = [[UILabel alloc] init];
    self.titleLabel.text = @"生理液异常";
    self.titleLabel.font = [UIFont systemFontOfSize:20.f];
    self.titleLabel.textColor = [UIColor colorWithHex:0xB0B1C9];
    [self.topView addSubview:self.titleLabel];
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.topView.mas_centerY);
        make.centerX.equalTo(self.topView.mas_centerX);
        make.height.equalTo(@(H(20)));
    }];
    
    self.contentLabel = [[UILabel alloc] init];
    self.contentLabel.text = @"你的生理液指标存在异常，健康可能存在隐患，如有情况及时就医哦";
    self.contentLabel.textColor = [UIColor colorWithHex:0x979697];
    self.contentLabel.numberOfLines = 0;
    self.contentLabel.font = [UIFont systemFontOfSize:11.f];
    [self.topView addSubview:self.contentLabel];
    [self.contentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.titleLabel.mas_bottom).offset(15);
        make.centerX.equalTo(self.topView.mas_centerX);
        make.width.equalTo(@(self.topView.width / 2));
    }];
    
    
    CAShapeLayer *backgroundLayer = [CAShapeLayer layer];
    backgroundLayer.lineWidth = 4;
    backgroundLayer.strokeColor = [UIColor colorWithHex:0xF6F6FA].CGColor;
    backgroundLayer.fillColor = [UIColor clearColor].CGColor;
    backgroundLayer.lineCap = kCALineCapRound;
    
    CGFloat pathX = self.backgroundView.width / 2;
    CGFloat pathY = self.topView.height / 2 + H(20) + H(7.5);
    CGFloat radius = self.backgroundView.width / 2 - W(50);
    
    UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(pathX, pathY) radius:radius startAngle:M_PI endAngle:2*M_PI clockwise:YES];
    backgroundLayer.path = path.CGPath;
    [self.topView.layer addSublayer:backgroundLayer];
    
    self.archLine = [CAShapeLayer layer];
    self.archLine.lineWidth = 4;
    self.archLine.strokeColor = [UIColor colorWithHex:0x9396B1].CGColor;
    self.archLine.fillColor = [UIColor clearColor].CGColor;
    self.archLine.lineCap = kCALineCapRound;
    
    self.archLine.path = [self getBezierLine:1.3];
    [self.topView.layer addSublayer:self.archLine];
    
}

- (CGPathRef)getBezierLine:(CGFloat)percentage {
    
    /* 设置半径为10 */
    CGFloat pathX = self.backgroundView.width / 2;
    CGFloat pathY = self.topView.height / 2 + H(20) + H(7.5);
    CGFloat radius = self.backgroundView.width / 2 - W(50);
    
    if (percentage >= 100) {
        percentage = 2;
    }else if (percentage >= 50) {
        percentage = (percentage - 50) / 10 * 0.1 + 1.5;
    }else if (percentage < 50) {
        percentage = percentage / 10 * 0.1 + 1;
    }
    
    UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(pathX, pathY) radius:radius startAngle:M_PI endAngle:percentage*M_PI clockwise:YES];
    
    return path.CGPath;
}

/**
 添加爱爱次数列表视图
 */
- (void)addLoveTimesView {
    CGFloat width = self.backgroundView.frame.size.width / 8;
    CGFloat height = (self.backgroundView.height - self.topView.height) / 2;
    UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc] init];
    flow.itemSize = CGSizeMake(width, height);
    flow.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    flow.minimumLineSpacing = 0;
    flow.minimumInteritemSpacing = 0;
    
    self.loveTimesCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, 0, 0) collectionViewLayout:flow];
    self.loveTimesCollectionView.delegate = self;
    self.loveTimesCollectionView.dataSource = self;
    self.loveTimesCollectionView.showsHorizontalScrollIndicator = NO;
    self.loveTimesCollectionView.backgroundColor = [UIColor whiteColor];
    [self.backgroundView addSubview:self.loveTimesCollectionView];
    [self.loveTimesCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.topView.mas_bottom);
        make.centerX.equalTo(self.backgroundView.mas_centerX);
        make.left.equalTo(self.backgroundView.mas_left);
        make.height.equalTo(@(height));
    }];
    
    
    
    UILabel *topLine = [[UILabel alloc] init];
    topLine.backgroundColor = [UIColor colorWithHex:0xf7f7f7];
    [self.backgroundView addSubview:topLine];
    [topLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.backgroundView.mas_centerX);
        make.left.equalTo(self.backgroundView.mas_left);
        make.height.equalTo(@(H(1)));
        make.top.equalTo(self.loveTimesCollectionView.mas_top);
    }];
    
    
    
    UILabel *bottomLine = [[UILabel alloc] init];
    bottomLine.backgroundColor = [UIColor colorWithHex:0xf7f7f7];
    [self.backgroundView addSubview:bottomLine];
    [bottomLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.backgroundView.mas_centerX);
        make.left.equalTo(self.backgroundView.mas_left);
        make.height.equalTo(@(H(1)));
        make.bottom.equalTo(self.loveTimesCollectionView.mas_bottom);
    }];
    /* 注册自定义单元格 */
    //    [self.lustDataCollectionView registerClass:[LustDataCollectionViewCell class] forCellWithReuseIdentifier:@"Cell"];
    [self.loveTimesCollectionView registerClass:[LoveTimesCollectionViewCell class] forCellWithReuseIdentifier:@"LoveTimesCell"];
    
    
}

- (void)addHealthData {
    
    NSMutableArray *viewArray = [NSMutableArray array];
    
    UIView *lastView = [[UIView alloc] init];
    lastView.backgroundColor = [UIColor clearColor];
    [self.backgroundView addSubview:lastView];
    [lastView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.loveTimesCollectionView.mas_bottom);
        make.centerX.equalTo(self.backgroundView.mas_centerX);
        make.bottom.equalTo(self.backgroundView.mas_bottom);
        make.width.equalTo(@(self.backgroundView.width));
    }];
    
    
    CGFloat viewWidth = self.backgroundView.width / 3;
    CGFloat viewHeight = (self.backgroundView.height - self.topView.height) / 4;
    
    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 3; j++) {
            UIView *view = [[UIView alloc] initWithFrame:CGRectMake(j * viewWidth, i * viewHeight, viewWidth, viewHeight)];
            [lastView addSubview:view];
            [viewArray addObject:view];
        }
    }
    
    UILabel *pregnancy = [[UILabel alloc] init];
    [self addHealthDataTitleLabel:pregnancy view:viewArray[0] labelText:@"怀孕几率"];
    self.pregnancyDataLabel = [[UILabel alloc] init];
    [self addHealthDataContentLabel:self.pregnancyDataLabel view:viewArray[0] labelText:@"80 %"];
    [self addBottomLine:viewArray[0]];
    [self addRightLine:viewArray[0]];
    
    
    UILabel *dysmenorrhea = [[UILabel alloc] init];
    [self addHealthDataTitleLabel:dysmenorrhea view:viewArray[1] labelText:@"痛经几率"];
    self.dysmenorrheaDataLabel = [[UILabel alloc] init];
    [self addHealthDataContentLabel:self.dysmenorrheaDataLabel view:viewArray[1] labelText:@"20 %"];
    [self addBottomLine:viewArray[1]];
    [self addRightLine:viewArray[1]];
    
    UILabel *physique = [[UILabel alloc] init];
    [self addHealthDataTitleLabel:physique view:viewArray[2] labelText:@"体质状况"];
    self.statusDataLabel = [[UILabel alloc] init];
    [self addHealthDataContentLabel:self.statusDataLabel view:viewArray[2] labelText:@"异常"];
    [self addBottomLine:viewArray[2]];
    
    UILabel *ph = [[UILabel alloc] init];
    [self addHealthDataTitleLabel:ph view:viewArray[3] labelText:@"生理液PH"];
    self.phDataLabel = [[UILabel alloc] init];
    [self addHealthDataContentLabel:self.phDataLabel view:viewArray[3] labelText:@"4.6"];
    [self addRightLine:viewArray[3]];
    
    UILabel *private = [[UILabel alloc] init];
    [self addHealthDataTitleLabel:private view:viewArray[4] labelText:@"私处紧实"];
    self.privateTightDataLabel = [[UILabel alloc] init];
    [self addHealthDataContentLabel:self.privateTightDataLabel view:viewArray[4] labelText:@"8"];
    [self addRightLine:viewArray[4]];
    
    UILabel *temperature = [[UILabel alloc] init];
    [self addHealthDataTitleLabel:temperature view:viewArray[5] labelText:@"私处温度"];
    self.temperatureDataLabel = [[UILabel alloc] init];
    [self addHealthDataContentLabel:self.temperatureDataLabel view:viewArray[5] labelText:@"38 °C"];

    
    
}

- (void)addBottomLine:(UIView *)view {
    UILabel *bottomLabel = [[UILabel alloc] init];
    bottomLabel.backgroundColor = [UIColor colorWithHex:0xf7f7f7];
    [self.backgroundView addSubview:bottomLabel];
    [bottomLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(view.mas_bottom).offset(0.5);
        make.left.equalTo(view.mas_left).offset(15);
        make.right.equalTo(view.mas_right).offset(-15);
        make.height.equalTo(@1);
    }];
}

- (void)addRightLine:(UIView *)view {
    UILabel *rightLabel = [[UILabel alloc] init];
    rightLabel.backgroundColor = [UIColor colorWithHex:0xf7f7f7];
    [self.backgroundView addSubview:rightLabel];
    [rightLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(view.mas_top).offset(15);
        make.bottom.equalTo(view.mas_bottom).offset(-15);
        make.left.equalTo(view.mas_right).offset(0.5);
        make.width.equalTo(@1);
    }];
}

- (void)addHealthDataContentLabel:(UILabel *)label view:(UIView *)view labelText:(NSString *)text {
    label.textColor = [UIColor colorWithHex:0x9699B3];
    label.font = [UIFont systemFontOfSize:25.f];
    NSRange range = [text rangeOfString:@" "];
    if (range.location == NSNotFound) {
        label.text = text;
    }else {
        label.attributedText = [self setCollectionCellContent:text];
    }
    [view addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(view.mas_centerY);
        make.centerX.equalTo(view.mas_centerX);
        make.height.equalTo(@25);
    }];
}

- (void)addHealthDataTitleLabel:(UILabel *)label view:(UIView *)view labelText:(NSString *)text{
    label.text = text;
    label.textColor = [UIColor colorWithHex:0xC1BFBF];
    label.font = [UIFont systemFontOfSize:15.f];
    [view addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(view.mas_centerY).offset(-10);
        make.centerX.equalTo(view.mas_centerX);
        make.height.equalTo(@15);
    }];
}

/**
 设置集合视图单元格数量
 */
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {

    return self.loveTimes.count;

}


/**
 设置集合视图
 */
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {


        LoveTimesCollectionViewCell *loveTimesCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"LoveTimesCell" forIndexPath:indexPath];
        
        
        NSDictionary *dic = self.loveTimes[indexPath.row];
    
        CGFloat radHeight = [dic[@"physiology_score"] intValue] / 200.0 * 80;
        CGFloat height = H(radHeight) == 0 || H(radHeight) > W(8) ? H(radHeight) : W(8);
        
        NSString *str = dic[@"add_time"];
        int month = [[str substringWithRange:NSMakeRange(5, 2)] intValue];
        int day = [[str substringWithRange:NSMakeRange(8, 2)] intValue];
        int hour = [[str substringWithRange:NSMakeRange(11, 2)] intValue];
        int min = [[str substringWithRange:NSMakeRange(14, 2)] intValue];
        
        loveTimesCell.dateLabel.text = [NSString stringWithFormat:@"%d/%d",day,month];
        loveTimesCell.timeLabel.text = [NSString stringWithFormat:@"%d:%d",hour,min];
        loveTimesCell.dataViewHeight = height;
        loveTimesCell.dataViewWidth = W(8);
        loveTimesCell.dataView.cornerRadius = W(8) / 2;
        

    
        
        
        return loveTimesCell;
    

    
}




/**
 富文本：修改空格后面的文字大小
 
 @param content 传入内容
 @return 返回富文本
 */
- (NSAttributedString *)setCollectionCellContent:(NSString *)content {
    
    NSString *str = @" ";
    NSRange range = [content rangeOfString:str];
    NSInteger location = range.location;
    NSMutableAttributedString *str2 = [[NSMutableAttributedString alloc] initWithString:content];
    [str2 addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:14.f] range:NSMakeRange(location, content.length - location)];
    return str2;
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (collectionView == self.loveTimesCollectionView) {
        LoveTimesCollectionViewCell *cell = (LoveTimesCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
        
//        
        self.healthDic = self.loveTimes[indexPath.row];
        
        CGFloat score = [self.healthDic[@"physiology_score"] intValue];
        CGFloat ph = [self.healthDic[@"PH"] floatValue];
        if (score >= 115) {
            self.titleLabel.text = @"正常";
            self.contentLabel.text = @"你的体质非常正常，保持良好的饮食习惯和作息习惯";
            self.statusDataLabel.text = @"正常";
        }else if (score < 115 && ph < 4.8) {
            self.titleLabel.text = @"生理液异常";
            self.contentLabel.text = @"你的生理液指标异常，健康可能存在隐患，如有情况及时就医哦";
            self.statusDataLabel.text = @"异常";
        }else if (score < 115) {
            self.titleLabel.text = @"宫寒";
            self.contentLabel.text = @"你可能是宫寒体质哦，可以适当饮用姜茶、红糖水、如果严重，当心妇科疾病哦";
            self.statusDataLabel.text = @"宫寒";
        }
        
        CGFloat percent = score * 100 / 110;
        
        self.archLine.path = [self getBezierLine:percent];
        
        cell.dataViewWidth = W(15);
        cell.dataView.cornerRadius = W(15) / 2;
        cell.dataView.backgroundColor = [UIColor colorWithHex:0x9395B1];
        
        self.pregnancyDataLabel.attributedText = [self setCollectionCellContent:[NSString stringWithFormat:@"%@ %%",self.healthDic[@"pregnancy"]]];
        self.dysmenorrheaDataLabel.attributedText = [self setCollectionCellContent:[NSString stringWithFormat:@"%@ %%",self.healthDic[@"dysmenorrhea"]]];
        self.phDataLabel.text = self.healthDic[@"PH"];
        self.privateTightDataLabel.text = self.healthDic[@"private_tight"];
        self.temperatureDataLabel.attributedText = [self setCollectionCellContent:[NSString stringWithFormat:@"%@ °C",self.healthDic[@"temperature"]]];
        
        

    }
}

- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (collectionView == self.loveTimesCollectionView) {
        LoveTimesCollectionViewCell *cell = (LoveTimesCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
        
//        self.selectIndexPath = nil;
        
        cell.dataViewWidth = W(8);
        cell.dataView.cornerRadius = W(8) / 2;
        cell.dataView.backgroundColor = [UIColor gradientFromColor:[UIColor colorWithHex:0x9396B1] toColor:[UIColor colorWithHex:0xDBDBE4] withHeight:cell.dataView.height + 1];
        
    }
}


- (HealthDetailsViewModel *)viewModel {
    if (_viewModel == nil) {
        _viewModel = [[HealthDetailsViewModel alloc] initWithViewController:self];
    }
    return _viewModel;
}

- (void)bindViewModel {
    [super bindViewModel];
    @weakify(self);
    [RACObserve(self.viewModel, userLoveTimes) subscribeNext:^(id x) {
        @strongify(self);
        
        self.loveTimes = self.viewModel.userLoveTimes;
        [self.loveTimesCollectionView reloadData];
    }];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
